//
//  GQHDriverProfileController.m
//  Xanthium
//
//  Created by GuanQinghao on 02/05/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View
#import "GQHDriverProfileView.h"

#pragma mark Controller
#import "GQHDriverProfileController.h"

#import "GQHLengthController.h"
#import "GQHModelController.h"
#import "GQHPlateController.h"
#import "GQHAgreementController.h"

#pragma mark CocoaPods
#import <TZImagePickerController.h>

#pragma mark ----------Header End----------

@interface GQHDriverProfileController () <GQHDriverProfileViewDelegate,TZImagePickerControllerDelegate> {
    
#pragma mark Data
    /// 司机基本信息参数
    NSMutableDictionary *parameters;
    /// 选择的车辆照片
    UIImage *firstCarImage;
    UIImage *secondCarImage;
#pragma mark View
    /// 自定义根视图
    GQHDriverProfileView *rootView;
}

@end


@implementation GQHDriverProfileController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHDriverProfileView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    parameters = [NSMutableDictionary dictionary];
    [parameters setObject:USER_GET_ID forKey:@"userId"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"司机基本信息";
    [self.qh_rightButton setTitle:@"确定" forState:UIControlStateNormal];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
            
        case 0: {
            
            switch (indexPath.row) {
                    
                case 0: {
                    
                    /// 姓名
//                    [self qh_alertWithTitle:@"请输入姓名" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                        textField.placeholder = @"请输入姓名";
//
//                    } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                        UITextField *inputTextField = alertController.textFields.firstObject;
//                        if (inputTextField.text) {
//
//                            [parameters setObject:inputTextField.text forKey:@"empName"];
//                            [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:0];
//                        }
//                        [rootView.qh_tableView reloadData];
//
//                    } completion:nil];
                }
                    break;
                case 1: {
                    
                    /// 联系电话
//                    [self qh_alertWithTitle:@"请输入联系电话" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                        textField.placeholder = @"请输入联系电话";
//                        textField.keyboardType = UIKeyboardTypeNumberPad;
//
//                    } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                        UITextField *inputTextField = alertController.textFields.firstObject;
//                        if (inputTextField.text) {
//
//                            [parameters setObject:inputTextField.text forKey:@"phoneNum"];
//                            [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:1];
//                        }
//                        [rootView.qh_tableView reloadData];
//
//                    } completion:nil];
                }
                    break;
                case 2: {
                    
                    /// 身份证号
//                    [self qh_alertWithTitle:@"请输入身份证号" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                        textField.placeholder = @"请输入身份证号";
//                        textField.keyboardType = UIKeyboardTypeNumberPad;
//
//                    } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                        UITextField *inputTextField = alertController.textFields.firstObject;
//                        if (inputTextField.text) {
//
//                            [parameters setObject:inputTextField.text forKey:@"dirIdCard"];
//                            [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:2];
//                        }
//                        [rootView.qh_tableView reloadData];
//
//                    } completion:nil];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1: {
            
            switch (indexPath.row) {
                    
                case 0: {
                    
                    /// 车牌类型
                    GQHPlateController *plateController = [[GQHPlateController alloc] init];
                    plateController.qh_plateBlock = ^(NSString *plateID, NSString *plateName) {
                        
                        [parameters setObject:plateID forKey:@"licenseplatetypecode"];
                        [rootView.qh_contentArray qh_safetySetObject:plateName atIndex:3];
                        [rootView.qh_tableView reloadData];
                    };
                    plateController.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:plateController animated:YES];
                }
                    break;
                case 1: {
                    
//                    /// 车牌号
//                    [self qh_alertWithTitle:@"请输入车牌号" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                        textField.placeholder = @"请输入车牌号";
//
//                    } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                        UITextField *inputTextField = alertController.textFields.firstObject;
//                        if (inputTextField.text) {
//
//                            [parameters setObject:inputTextField.text forKey:@"licPlateNum"];
//                            [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:4];
//                        }
//                        [rootView.qh_tableView reloadData];
//
//                    } completion:nil];
                }
                    break;
                case 2: {
                    
                    /// 车型
                    GQHModelController *modelController = [[GQHModelController alloc] init];
                    modelController.qh_modelBlock = ^(NSString *modelID, NSString *modelName) {
                        
                        [parameters setObject:modelID forKey:@"vehicleclassificationcode"];
                        [rootView.qh_contentArray qh_safetySetObject:modelName atIndex:5];
                        [rootView.qh_tableView reloadData];
                    };
                    modelController.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:modelController animated:YES];
                }
                    break;
                case 3: {
                    
                    /// 车长
                    GQHLengthController *lengthController = [[GQHLengthController alloc] init];
                    lengthController.qh_lengthBlock = ^(NSString *lengthID, NSString *lengthName) {
                        
                        [parameters setObject:lengthID forKey:@"carLength"];
                        [rootView.qh_contentArray qh_safetySetObject:lengthName atIndex:6];
                        [rootView.qh_tableView reloadData];
                    };
                    lengthController.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:lengthController animated:YES];
                }
                    break;
                case 4: {
                    
//                    /// 车辆载重
//                    [self qh_alertWithTitle:@"请输入车辆载重" message:nil inputHandler:^(UITextField * _Nullable textField) {
//
//                        textField.placeholder = @"请输入车辆载重";
//                        textField.keyboardType = UIKeyboardTypeDecimalPad;
//
//                    } actionHandler:^(UIAlertAction * _Nullable action, UIAlertController * _Nonnull alertController) {
//
//                        UITextField *inputTextField = alertController.textFields.firstObject;
//                        if (!inputTextField.text) {
//
//                            [self showToastWithText:@"车辆载重不能为空"];
//
//                            return;
//                        }
//
//                        if (!([inputTextField.text qh_isValidDecimal] || [inputTextField.text qh_isOnlyNumber])) {
//
//                            [self showToastWithText:@"车辆载重必须是整数或小数"];
//
//                            return;
//                        }
//
//                        if (0.0f == [inputTextField.text doubleValue]) {
//
//                            [self showToastWithText:@"车辆载重不能为零"];
//
//                            return;
//                        }
//                        if (inputTextField.text) {
//
//                            [parameters setObject:inputTextField.text forKey:@"carLoad"];
//                            [rootView.qh_contentArray qh_safetySetObject:inputTextField.text atIndex:7];
//                        }
//                        [rootView.qh_tableView reloadData];
                    
//                    } completion:nil];
                }
                    break;
                case 5: {
                    
                    /// 车辆照片
                    TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:2 delegate:self];
                    imagePickerController.allowTakePicture = NO;
                    [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                        DLog(@"选择图片完成,上传图片");
                        
                        if (photos && photos.count > 0) {
                            
                            rootView.qh_leftImageView.image = [UIImage qh_imageWithColor:kLightGrayColor];
                            rootView.qh_rightImageView.image = [UIImage qh_imageWithColor:kLightGrayColor];
                            
                            if (1 == photos.count) {
                                
                                rootView.qh_rightImageView.image = firstCarImage = photos[0];
                                [rootView.qh_tableView reloadData];
                            }
                            
                            if (2 == photos.count) {
                                
                                rootView.qh_rightImageView.image = firstCarImage = photos[0];
                                rootView.qh_leftImageView.image = secondCarImage = photos[1];
                                [rootView.qh_tableView reloadData];
                            }
                        }
                    }];
                    
                    [self presentViewController:imagePickerController animated:YES completion:nil];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark --TargetMethod
- (void)qh_clickedRightButton:(UIButton *)sender {
    
    NSArray * keys = @[@"empName",
                       @"phoneNum",
                       @"dirIdCard",
                       @"",
                       @"licPlateNum",
                       @"",
                       @"",
                       @"carLoad"];
    for (int i = 0; i < keys.count; i ++)
    {
        NSString * key = keys[i];
        NSString * value = rootView.qh_contentArray[i];
        if (![key isEqualToString:@""])
        {
            [parameters setObject:value forKey:key];
        }
        
    }
    
    if (![parameters objectForKey:@"userId"]) {
        
        [self showToastWithText:@"用户信息出错"];
        return;
    }
    
    if (![parameters objectForKey:@"empName"]) {
        
        [self showToastWithText:@"请输入联系人姓名"];
        return;
    }
    
    if (![parameters objectForKey:@"phoneNum"]) {
        
        [self showToastWithText:@"请输入联系电话"];
        return;
    }
    
    if (![[parameters objectForKey:@"phoneNum"] qh_isValidMobile]) {
        
        [self showToastWithText:@"请输入有效的联系电话"];
        return;
    }
    
    if (![parameters objectForKey:@"dirIdCard"]) {
        
        [self showToastWithText:@"请输入身份证号码"];
        return;
    }
    
    if (![[parameters objectForKey:@"dirIdCard"] qh_isValidIdentityCardNo]) {
        
        [self showToastWithText:@"请输入有效的身份证号码"];
        return;
    }
    
    if (![parameters objectForKey:@"licPlateNum"]) {
        
        [self showToastWithText:@"请输入车牌号"];
        return;
    }
    
    if (![parameters objectForKey:@"vehicleclassificationcode"]) {
        
        [self showToastWithText:@"请选择车型"];
        return;
    }
    
    if (![parameters objectForKey:@"carLength"]) {
        
        [self showToastWithText:@"请选择车长"];
        return;
    }
    
    if (![parameters objectForKey:@"licenseplatetypecode"]) {
        
        [self showToastWithText:@"请选择车牌类型"];
        return;
    }
    
    if (![parameters objectForKey:@"carLength"]) {
        
        [self showToastWithText:@"请选择车长"];
        return;
    }
    
    if (![parameters objectForKey:@"carLoad"]) {
        
        [self showToastWithText:@"请输入车辆载重"];
        return;
    }
    
    if (0 == [[parameters objectForKey:@"carLoad"] integerValue]) {
        
        [self showToastWithText:@"车辆载重不能为0"];
        return;
    }
    
    [self qh_loadLoadingView];
    [self uploadImagesWithSuccess:^(NSNumber *code, NSString *message, NSDictionary *data) {
        DLog(@"%@-%@-%@",code,message,data);
        [self qh_removedLoadingView];
        
        if (0 == [code integerValue]) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"05" forKey:USER_STATUS];
            [self showToastWithText:@"司机基本信息提交成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        } else {
            
            [self showToastWithText:message];
        }
    }];
}

- (void)qh_checkAgreement
{
    GQHAgreementController *agreementController = [[GQHAgreementController alloc] init];
    agreementController.qh_agreementType = GQHAgreementTypeAuthorization;
    [self presentViewController:agreementController animated:YES completion:nil];
}

- (void)qh_selectAgreement:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        
        self.qh_rightButton.userInteractionEnabled = YES;
        [self.qh_rightButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    } else {
        
        self.qh_rightButton.userInteractionEnabled = NO;
        [self.qh_rightButton setTitleColor:kGrayColor forState:UIControlStateNormal];
    }
}

#pragma mark --PrivateMethod
/// 上传图片
- (void)uploadImagesWithSuccess:(void(^)(NSNumber *code, NSString *message, NSDictionary *data))success {
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/myInformation/1/diverAut1"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manager POST:APIURLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *firstImageData = UIImagePNGRepresentation(firstCarImage);
        NSData *secondImageData = UIImagePNGRepresentation(secondCarImage);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        NSString *name = [formatter stringFromDate:[NSDate date]];
        
        NSString *firstFileName = [NSString stringWithFormat:@"%@1.png", name];
        NSString *secondFileName = [NSString stringWithFormat:@"%@2.png", name];
        
        if (firstCarImage) {
            
            [formData appendPartWithFileData:firstImageData name:@"CarPhoto" fileName:firstFileName mimeType:@"image/png"];
        }
        
        if (secondCarImage) {
            
            [formData appendPartWithFileData:secondImageData name:@"CarPhoto1" fileName:secondFileName mimeType:@"image/png"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            
            NSNumber *responseCode = [responseObject objectForKey:@"code"];
            NSString *responseMessage = [responseObject objectForKey:@"msg"];
            NSDictionary *responseData = [responseObject objectForKey:@"data"];
            
            success(responseCode,responseMessage,responseData);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
